<template>
  <a-card :bordered="false">
    <upload-modal ref="uploadModalRef" size="small" :url="url" @sync="search" :file-list="fileList" />

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form  @keyup.enter="search">
        <a-row :gutter="24">
          <a-col :md="5" :sm="5">
            <a-form-item label="客户名称">
              <a-select allowClear showSearch optionFilterProp="children"
                        :filter-option="false"
                        @search="(value) => searchTextForClients=value"
                        :options="customizedFilterOptions(searchTextForClients, checkBillStore.clients)"
                        v-model:value="queryParams.id_client">
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="5">
            <a-form-item label="文件搜索" :offset="1">
              <a-input placeholder="请输入关键字" v-model:value="queryParams.fileName" />
            </a-form-item>
          </a-col>
          <a-col :md="1" :sm="1" :offset="1">
            <a-form-item>
              <a-button v-show="selectedRowKeys.length > 0" @click.prevent="deleteMany" type="primary" danger>删除</a-button>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="2">
            <a-form-item>
              <a-button @click.prevent="search" type="default">查询</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" @click="handleAdd"><PlusOutlined />新增</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
          style="font-weight: 600">{{selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        size="small"
        bordered
        rowKey="filePath"
        :columns="columns"
        :dataSource="dataSourceFiltered"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange"
      >
        <template #action="{ text, record }">
          <a @click="ossDelete(record.filePath)">删除</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多<DownOutlined/></a>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="editMemo(record)">
                  备注
                </a-menu-item>
                <a-menu-item v-if="canPreview(record)" @click="view(record)">
                    预览
                </a-menu-item>
                <a-menu-item  @click="handleDownload(record)">
                  下载
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->
    <a-modal :open="previewVisible" width="60%" :footer="null" tile="图片预览" @cancel="imgPreviewClose">
      <a-card>
        <img alt="preview" style="width: 100%" :src="previewImage" />
      </a-card>
    </a-modal>
  </a-card>
</template>


<script setup>
import { ref, computed, onMounted } from 'vue';
import { deleteAction, downFile, getAction } from "@/utils/request";
import { message, Modal } from 'ant-design-vue';
import UploadModal from '@/views/modules/UploadModal';
import { commonConf } from "@/utils/my.js";
import useCheckBillStore from "@/store/modules/checkBill.js";
import { getToken } from "@/utils/auth.js";
import { customizedFilterOptions } from '@/utils/my';
import { useRouter } from 'vue-router'

const router = useRouter()

/*store*/
const checkBillStore = useCheckBillStore()
checkBillStore.getPortsAndClient()
/*data*/
const selectedRowKeys = ref([])
const selectedRows = ref([])
const dataSource = ref([])
const loading = ref(false)
const searchTextForClients = ref('')
////reactive+refs
const data = reactive({
  queryParams: {
    id_client: undefined,
    fileName: undefined,
  },
  ipagination: commonConf("ipagination")
});
const { queryParams, ipagination} = toRefs(data);

// 定义组件引用
const uploadModalRef = ref(null);
const pdfModalRef = ref(null);

// 定义响应式数据
const previewVisible = ref(false);
const previewImage = ref('');
const disabled = ref({
  client: false
});
const fileList = ref([]);
const field = ref('create_time');
const order = ref('descend');
// simple vars
const imageType = ['png', 'jpeg', 'jpg', 'gif']
const pdfType = ['pdf']
const bucketName = 'contract'
const url = {
  getMultiDataBySql: '/reportConfig/config/getMultiDataBySql',
  getDataBySql: '/reportConfig/config/getDataBySql',
  oss: "/oss/",
  list: "/oss/",
  delete: "/oss/",
  pdf_preview: "/preview/web/viewer.html"
}
let client = {}
//// 定义表头
// 提取文件大小转换函数
const formatFileSize = (size) => {
  if (typeof size !== 'number') return '';
  if (size >= 1024 * 1024) {
    return `${Math.round(size / (1024 * 1024))}M`;
  } else if (size >= 1024) {
    return `${Math.round(size / 1024)}K`;
  } else {
    return `${size}b`;
  }
};
const columns = ref([
  {
    title: '#', dataIndex: '', key: 'rowIndex', width: "2%", align: "center",
    customRender: ({_, __, index}) => parseInt(index) + 1
  },
  {
    title: '文件名称', align: "left", sorter: true, width: '20%',
    dataIndex: 'filePath'
  },
  {
    title: '大小', align: "right", width: '4%', dataIndex: 'size',
    customRender: ({text: t}) => formatFileSize(t)
  },
  {
    title: '备注', align: "left", sorter: true, width: '56%',
    dataIndex: 'memo'
  },
  {
    title: '创建日期', align: "center", sorter: true, width: '9%',
    dataIndex: 'create_time'
  },
  {
    title: '操作', width: '9%', dataIndex: 'action', align: "center",
    slots: { customRender: 'action' }
  }
]);


// 计算属性
const dataSourceFiltered = computed(() => {
  let data = dataSource.value;
  if (queryParams.value.fileName) {
    data = data.filter((d) =>
      (d.filePath?.includes(queryParams.value.fileName) || d.memo?.includes(queryParams.value.fileName))
    );
  }
  ipagination.value.total = data.length;
  return data;
});

/*method*/
const search = async () => {
  try {
    await getOssFiles();
  } catch (error) {
    message.error('查询失败，请稍后重试');
    console.error('查询失败', error);
  }
};

const handleTableChange = (newPagination, filters, sorter) => {
  ipagination.value = newPagination;
  if (sorter) {
    field.value = sorter.field;
    order.value = sorter.order;
  }
  search();
};

const checkBeforeUpload = () => {
  client = checkBillStore.clients.find((c) => c.value === queryParams.value.id_client);
  if (!client) {
    message.error('请先选择客户！');
    fileList.value.pop();
    return false;
  }
  return true;
};

const handleAdd = () => {
  if (checkBeforeUpload()) {
    let data = {
      bizPath: `${client.label}/`,
      bucketName: bucketName,
      id_client: queryParams.value.id_client
    };
    uploadModalRef.value?.add(data);
    fileList.value.length = 0;
  }
};

const onSelectChange = (newSelectedRowKeys, newSelectedRows) => {
  selectedRowKeys.value = newSelectedRowKeys;
  selectedRows.value = newSelectedRows;
};

const onClearSelected = () => {
  selectedRowKeys.value = [];
  selectedRows.value = [];
};

const canPreview = (params) => {
  const type = params.filePath?.split(".").pop();
  return type && (imageType.includes(type) || pdfType.includes(type));
};

const view = (params) => {
  const type = params.filePath?.split(".").pop();
  if (pdfType.includes(type)) {
    pdfPreview(params);
  }
  if (imageType.includes(type)) {
    imgPreview(params);
  }
};

const imgPreview = (params) => {
  previewImage.value = `${import.meta.env.VITE_APP_BASE_API}${url.oss}read?filePath=${params.filePath}`;
  previewVisible.value = true;
};

const imgPreviewClose = () => {
  previewImage.value = '';
  previewVisible.value = false;
};

const pdfPreview = (params) => {
  const file  = `${import.meta.env.VITE_APP_BASE_API}${url.oss}read?filePath=${params.filePath}`
  url.pdf_preview = `${import.meta.env.VITE_APP_BASE_API}${url.pdf_preview}?file=${encodeURIComponent(file)}`
  // 使用window.open打开新窗口
  window.open(url.pdf_preview, '_blank');
};

const handleDownload = async (params) => {
  params.bucketName = bucketName;
  try {
    const data = await downFile(`${url.oss}download`, { ...params });
    if (!data) {
      message.warning('文件下载失败');
      return;
    }
    const result = await data.text();
    if (result.includes("message") && result.includes("success")) {
      let msg = '';
      try {
        const res = JSON.parse(result);
        msg = res.message;
      } catch (e) {
        console.error(e);
        msg = result;
      }
      message.error(msg, 10);
      return;
    }
    const fileName = params.filePath?.split('/').pop() || 'downloaded_file';
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), fileName);
    } else {
      const blobUrl = window.URL.createObjectURL(new Blob([data]));
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = blobUrl;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(blobUrl);
    }
  } catch (error) {
    console.error('下载失败', error);
    message.error('文件下载失败，请稍后重试');
  }
};

const getOssFiles = async () => {
  loading.value = true
  client = checkBillStore.clients.find((i) => i.value === queryParams.value.id_client);
  try {
    const res = await getAction(url.list, {
      bucketName: bucketName,
      bizPath: client?.label,
      filePath: queryParams.value.fileName
    });
    if (res && res.success && Array.isArray(res.data)) {
      res.data.sort((a, b) => {
        if (order.value === 'descend') {
          return a[field.value] < b[field.value] ? -1 : a[field.value] > b[field.value] ? 1 : 0;
        } else {
          return a[field.value] < b[field.value] ? 1 : a[field.value] > b[field.value] ? -1 : 0;
        }
      });
      dataSource.value = res.data;
      loading.value = false;
    }
  } catch (error) {
    throw error;
  }
};

const deleteMany = () => {
  Modal.confirm({
    title: '确认删除',
    content: '是否删除选中文件?',
    onOk: async () => {
      try {
        const res = await deleteAction(url.oss, { bucketName: bucketName }, { filePaths:selectedRowKeys.value });
        if (res.success) {
          selectedRowKeys.value = [];
          selectedRows.value = [];
          search();
          message.success('删除成功');
        } else {
          message.error('删除失败！');
        }
      } catch (error) {
        console.error('删除失败', error);
        message.error('删除失败，请稍后重试！');
      }
    }
  });
};

const editMemo = (record) => {
  fileList.value = [];
  uploadModalRef.value?.edit(record);
};

const ossDelete = (filePath, callback) => {
  Modal.confirm({
    title: '确认删除',
    content: '是否删除此文件?',
    onOk: async () => {
      try {
        const res = await deleteAction(url.oss, { bucketName: bucketName, filePath: filePath });
        if (res.success) {
          search();
          message.success('删除成功');
        }
        if (callback && typeof callback === 'function') {
          callback();
        }
      } catch (error) {
        console.error('删除失败', error);
        message.error('删除失败，请稍后重试');
      }
    }
  });
};


</script>

<style scoped>
  table {
    font-size: 10px!important;
  }
</style>
